package com.partners.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.partners.configure.RedisConfigurtion;
import com.partners.model.Member;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * session工具类
 * @author liangyongle
 * @date 2018/8/20 0020
 */
@Component
public class SessionManager {



    /**
     *  redisTemplate
     */
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RedisConfigurtion redisConfigurtion;
    /**
     * key前缀
     */
    private static final String KEY_PREFIX = "session::";

    private static final String TOKEN_PREFIX = "token::";

    /**
     *  session有效时长为30分钟
     */
    private static final Duration SESSION_DURATION = Duration.ofMinutes(30L);





    /**
     * 缓存基本的对象，Integer、String、实体类等
     * @param key     缓存的键值
     * @param value   缓存的值
     * @param expire  过期时间(单位:秒),传入 -1 时表示不设置过期时间
     * @return        缓存的对象
     */
    public boolean setCacheObject(String key, Object value, long expire) {
        boolean result= false;
        redisTemplate.opsForValue().set(key,value);
        if (expire != -1) {
            result = redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return result;
    }

    /**
     * 删除一个键值
     * @param key     缓存的键
     * @return    void
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }


    /**
     * 获得缓存的多个对象。
     * @param key        缓存键值
     * @return            缓存键值对应的数据
     */
    public JSONObject getCacheJsonObject(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        if(o != null){
            JSONObject json = JSONObject.parseObject(o.toString()) ;
            return json;
        }
        return null;
    }

    /**
     * 获得缓存的基本对象。
     * @param key        缓存键值
     * @return            缓存键值对应的数据
     */
    public Object getCacheObject(String key){
        Object res = redisTemplate.opsForValue().get(key);
        if(res != null){
            return res;
        }
        return null;
    }


    /**
     * 获取key剩余时间
     * @param key
     * @return
     */
    public long getExpireTime(String key){
        return redisTemplate.getExpire(key);
    }


    /**
     * 根据Session转换为对象
     * @param session
     * @return
     */

     public JSONObject JsonSession(HttpSession session){
         Object fansInfo = session.getAttribute("openId");
         JSONObject jsonObject = JSON.parseObject(JsonUtils.toJson(fansInfo));
         return jsonObject;
     }

     /**
     *生成token
     * */

     public  String saveAndCreateTokens(Member member) {
         String token = UUID.randomUUID().toString();
         String key = generateKey(token);
         redisTemplate.opsForValue().set(key,member,SESSION_DURATION.toMinutes(),TimeUnit.MINUTES);
         return token;
     }


/**
 //     * 生成key
 //     * @param token token
 //     * @return key
 //     */
    private static String generateKey(String token) {
        return KEY_PREFIX + token;
    }
    /**
     * 生成token
     * @param yaLiSession yaLiSession
     * @return token
     */


    /**
     * 获取当前请求的token
     * @return
     */
    public static String currentThreadToken() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        return request.getHeader("token");
    }

    public void updateMemberTokenContent(String token, Member member) {
        redisTemplate.opsForValue().set(TOKEN_PREFIX+token,member,SESSION_DURATION.toMinutes(), TimeUnit.MINUTES);

    }
}
